package study.springboot.starter.redis.template;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Slf4j
@Configuration
//@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisXAutoConfiguration {

    @Bean
//    @ConditionalOnBean({LettuceConnectionFactory.class, JedisConnectionFactory.class})
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        log.info(">>>>>> create RedisTemplate");
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);

        //序列化器
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        //key
        redisTemplate.setKeySerializer(stringSerializer);
        //String value
        redisTemplate.setValueSerializer(stringSerializer);
        //hash key
        redisTemplate.setHashKeySerializer(stringSerializer);
        //hash value
        redisTemplate.setHashValueSerializer(stringSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    @ConditionalOnBean(RedisTemplate.class)
    public RedisXClient redisXClient(RedisTemplate redisTemplate) {
        log.info(">>>>>> create RedisXClient");
        return new RedisXClient(redisTemplate);
    }
}
